//
//  UserAccount.swift
//  Weibo
//
//  Created by apple on 15/12/9.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
//用户的账户信息
class UserAccount: NSObject, NSCoding {
    
    
    // 用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    //access_token的生命周期，单位是秒数。
    //一旦从服务器获得过期的时间 立刻计算准确的时间
    var expires_in: NSTimeInterval = 0 {
    
        didSet{
            //计算过期的日期
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        
        }
    }
    //过期日期
    var expiresDate: NSDate?
    //当前授权用户的UID。
    var uid: String?
    //用户昵称
    var screen_name: String?
    //用户头像地址（大图） 180*180像素
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
    
        let keys = ["access_token", "expires_in","expiresDate", "uid"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    //保存当前对象
    func saveUserAccount() {
    
        //1 给个保存路径
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        //2  从Xcode7  bate5开始stringByAppendingPathComponent 转为NSSTing 特有
        //单纯的  as  在Swift中只有三个地方会被桥接
        //string as nsstring
        //nasrray as [array]
        //nsdictionary as [nstring: anyobject]
        
        path = (path as NSString).stringByAppendingPathComponent("account.plist")
        
        // 在实际开发中一定要确认文件真的保存了
        print(path)
        
        //3 归档保存
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
    }

    //MARK 归档  键值的归档 和  解档  先遵守NSCoding协议
    
    //归档把当前对象保存到磁盘中 将对象编码成二进制数 类似于网络的序列化 
    //编码器 aCoder

    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    //解档 从磁盘中加载二进制数据  转换成对象调用 跟网络的反序列化很像
    //解码器 aDecoder
    required init?(coder aDecoder: NSCoder) {
      
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
    }
    
}
